<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

/**
 * 支付回调类
 **/
class Notify extends Controller
{
    public function notice()
    {
        $data = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA)), true);

//        file_put_contents(RUNTIME_PATH . 'pay.txt', json_encode($data, JSON_UNESCAPED_UNICODE));

        //业务处理代码请自行实现
        if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {

            //订单号
            $order_sn = $data['out_trade_no'];

            //查询订单支付状态；0：未支付；1：已支付
            $is_pay = Db::name('order')->where(['pay_order_sn' => $order_sn])->value('is_pay');
            if ($is_pay == 0) {
                Db::startTrans();
                try {
                    $this->doOrder($order_sn);

                    echo 'SUCCESS';
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }

        }
    }

    /**
     * 支付成功处理订单业务逻辑
     * @param string $order_sn 支付订单号
     * */
    public function doOrder($order_sn)
    {
        $order_info = Db::name('order')->where(['pay_order_sn' => $order_sn])->find();

        $order_id = $order_info['id'];
        $time = time();

        // 1：修改订单支付状态
        $update_order_data = [
            'is_pay' => 1,
            'status' => 2,
            'pay_time' => $time,
            'update_time' => $time
        ];
        Db::name('order')->where(['id' => $order_id])->update($update_order_data);

        // 3：增加销量
        /*$vice_order_list = Db::name('vice_order')->where(['order_id' => $order_id])->select();
        if ($vice_order_list) {
            foreach ($vice_order_list as &$v) {
                Db::name('goods')->where(['id' => $v['goods_id']])->setInc('sales_count', $v['count']);
            }
        }*/
    }

}